<template>
  <view class="index-container">
    <!-- 顶部搜索栏 -->
    <view class="search-container">
      <view class="search-box" @click="goToSearch">
        <text class="iconfont icon-search"></text>
        <text class="search-placeholder">搜索图书、作者、关键词</text>
      </view>
    </view>
    
    <!-- 轮播图 -->
    <swiper class="banner-swiper" circular indicator-dots autoplay :interval="3000" :duration="500">
      <swiper-item v-for="(item, index) in bannerList" :key="index">
        <image 
          :src="item.image" 
          mode="aspectFill" 
          class="banner-image" 
          @click="handleBannerClick(item)"
          @error="handleImageError(index)"
        ></image>
      </swiper-item>
    </swiper>
    

    
    <!-- 分类导航 -->
    <view class="category-nav">

      <scroll-view scroll-x class="category-scroll" show-scrollbar="true">
        <view 
          class="category-item" 
          v-for="(item, index) in categories" 
          :key="index"
          :class="{ active: currentCategory === item.id }"
          @click="changeCategory(item.id)"
          :style="{'background-color': index % 2 === 0 ? '#f0f8ff' : '#e6f3ff'}"
        >
          <text class="category-text">{{ item.name }}</text>
          <!-- 显示分类下的图书数量，除了"全部"分类外都显示数量 -->
          <text v-if="item.id !== 'all' && item.bookCount !== undefined" class="category-count">({{ item.bookCount }})</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 内容加载中 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 内容主体区域 -->
    <view class="content-container" v-else>
      <!-- 个性化推荐区域 -->
      <view class="section-container" v-if="bookStore.personalRecommendations.length > 0">
        <view class="section-header">
          <text class="section-title">专属推荐</text>
          <view class="section-more" @click="goToMore('recommendation')">
            <text>查看更多</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        <scroll-view scroll-x class="book-scroll">
          <view 
            class="book-card" 
            v-for="(book, index) in bookStore.personalRecommendations" 
            :key="'personal-'+index"
            @click="goToBookDetail(book.id)"
          >
            <image class="book-cover" :src="book.coverUrl" mode="aspectFill"></image>
            <text class="book-title">{{book.title}}</text>
            <view class="book-rating">
              <uni-rate :value="book.avgRating" size="14" :readonly="true" :is-fill="false"></uni-rate>
              <text class="rating-text">{{book.avgRating || 0}}</text>
            </view>
          </view>
        </scroll-view>
      </view>
      
      <!-- 热门图书区域 -->
      <view class="section-container">
        <view class="section-header">
          <text class="section-title">热门图书</text>
          <view class="section-more" @click="goToMore('hot')">
            <text>查看更多</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        <view class="book-grid">
          <view 
            class="book-item" 
            v-for="(book, index) in bookStore.hotBooks" 
            :key="'hot-'+index"
            @click="goToBookDetail(book.id)"
          >
            <image class="book-cover" :src="book.coverUrl" mode="aspectFill"></image>
            <text class="book-title">{{book.title}}</text>
            <view class="book-author">{{book.author}}</view>
            <view class="book-rating">
              <uni-rate :value="book.avgRating" size="12" :readonly="true" :is-fill="false"></uni-rate>
              <text class="rating-text">{{book.avgRating || 0}}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 新书上架区域 -->
      <view class="section-container">
        <view class="section-header">
          <text class="section-title">新书上架</text>
          <view class="section-more" @click="goToMore('new')">
            <text>查看更多</text>
            <text class="iconfont icon-right"></text>
          </view>
        </view>
        <view class="book-list">
          <view 
            class="book-list-item" 
            v-for="(book, index) in bookStore.newBooks" 
            :key="'new-'+index"
            @click="goToBookDetail(book.id)"
          >
            <image class="book-cover" :src="book.coverUrl" mode="aspectFill"></image>
            <view class="book-info">
              <text class="book-title">{{book.title}}</text>
              <text class="book-author">{{book.author}}</text>
              <text class="book-desc">{{formatText(book.description, 60)}}</text>
              <view class="book-meta">
                <view class="book-rating">
                  <uni-rate :value="book.avgRating" size="12" :readonly="true" :is-fill="false"></uni-rate>
                  <text class="rating-text">{{book.avgRating || 0}}</text>
                </view>
                <text class="book-category">{{book.categoryName}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部内容 -->
      <view class="footer">
        <uni-load-more :status="loadMoreStatus" :contentText="loadingText"></uni-load-more>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, onMounted, reactive, onUnmounted } from 'vue';
import { useBookStore } from '@/store/book.js';
import { useUserStore } from '@/store/user.js';

export default {
  name: 'IndexPage',
  // 页面的生命周期钩子，支持下拉刷新
  onPullDownRefresh() {
    // 调用内部定义的刷新方法
    this.onPullDownRefresh && this.onPullDownRefresh();
  },
  
  // 页面显示时不再主动检查登录状态，避免登录页面冲突
  onShow() {
    console.log('首页显示');
  },
  setup() {
    // 获取图书数据存储实例
    const bookStore = useBookStore();
    const userStore = useUserStore();
    
    // 记录是否已登录，用于状态切换时决定是否刷新数据
    const wasLoggedIn = ref(userStore.isLoggedIn);
    
    // 页面数据 - 使用线上图片替代本地图片，确保能正常显示
    const bannerList = ref([
      { 
        id: 1, 
        image: 'https://img-cdn.uniapp.dcloud.net.cn/uniapp/doc/poster.png', 
        type: 'book', 
        targetId: 1001 
      },
      { 
        id: 2, 
        image: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni-app.png', 
        type: 'category', 
        targetId: 5 
      },
      { 
        id: 3, 
        image: 'https://web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg', 
        type: 'promotion', 
        targetId: 'summer2023' 
      }
    ]);
    
    // 图片加载失败处理函数
    function handleImageError(index) {
      console.log('图片加载失败, 索引:', index);
      // 当图片加载失败时使用默认图片
      if (bannerList.value[index]) {
        try {
          bannerList.value[index].image = 'static/images/default-banner.png';
          console.log('已切换为默认图片');
        } catch (err) {
          console.error('替换图片失败:', err);
        }
      }
    }
    
    const categories = ref([]);
    const currentCategory = ref('all');
    const isLoading = ref(true);
    const loadMoreStatus = ref('more');
    
    const loadingText = {
      contentdown: '上拉显示更多',
      contentrefresh: '数据加载中...',
      contentnomore: '没有更多数据了'
    };
    
    // 初始化方法
    // 登录状态变化事件监听
    function setupLoginStateListener() {
      // 监听登录状态变化的全局事件
      uni.$on('loginStateChanged', handleLoginStateChange);
    }
    
    // 登录状态变化处理函数
    function handleLoginStateChange(event) {
      console.log('检测到登录状态变化:', event);
      
      // 只有当登录状态真正发生变化时才执行刷新
      if (event.loggedIn !== wasLoggedIn.value) {
        wasLoggedIn.value = event.loggedIn;
        
        if (event.loggedIn) {
          console.log('用户已登录，刷新数据...');
          // 用户登录后刷新推荐数据（因为可能包含个性化内容）
          loadPersonalRecommendations();
        } else {
          console.log('用户已退出登录，刷新数据...');
          // 用户退出登录后刷新数据（加载非个性化内容）
          refreshPageData();
        }
      }
    }
    
    // 检查登录状态，供页面 onShow 函数调用
    function checkLoginStatus() {
      // 添加缓存以检测用户是否正在尝试登录
      const currentRoute = getCurrentPageRoute();
      
      // 如果用户正在访问登录页面，不进行重定向
      if (currentRoute && currentRoute.indexOf('/pages/login/') !== -1) {
        console.log('检测到用户正在访问登录页面，不进行状态检查');
        return;
      }
      
      const currentLoginStatus = userStore.isLoggedIn;
      console.log('检查登录状态:', currentLoginStatus, '之前状态:', wasLoggedIn.value);
      
      // 如果登录状态发生了变化
      if (currentLoginStatus !== wasLoggedIn.value) {
        wasLoggedIn.value = currentLoginStatus;
        refreshPageData();
      }
    }
    
    // 获取当前页面路由
    function getCurrentPageRoute() {
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1];
        return currentPage.route || currentPage.$page?.fullPath || '';
      }
      return '';
    }
    
    // 刷新页面所有数据的函数
    function refreshPageData() {
      isLoading.value = true;
      console.log('开始刷新页面数据...');
      
      Promise.all([
        loadCategories(),
        loadHotBooks(),
        loadNewBooks(),
        loadPersonalRecommendations()
      ]).then(() => {
        console.log('页面数据刷新完成');
        isLoading.value = false;
      }).catch((error) => {
        console.error('页面数据刷新失败:', error);
        isLoading.value = false;
      });
    }
    
    onMounted(async () => {
      try {
        // 设置登录状态监听器
        setupLoginStateListener();
        
        // 加载分类数据
        await loadCategories();
        
        // 同时并行加载其他数据
        await Promise.all([
          loadHotBooks(),
          loadNewBooks(),
          loadPersonalRecommendations()
        ]);
        
        isLoading.value = false;

      } catch (error) {
        console.error('首页数据加载失败:', error);
        uni.showToast({
          title: '数据加载失败，请下拉刷新重试',
          icon: 'none'
        });
        isLoading.value = false;
      }
    });
    
    // 组件卸载时移除事件监听
    onUnmounted(() => {
      uni.$off('loginStateChanged', handleLoginStateChange);
    });
    
    // 下拉刷新
    function onPullDownRefresh() {
      // 重新加载所有数据
      Promise.all([
        loadCategories(),
        loadHotBooks(),
        loadNewBooks(),
        loadPersonalRecommendations()
      ]).then(() => {
        uni.stopPullDownRefresh();
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        });
      }).catch(() => {
        uni.stopPullDownRefresh();
        uni.showToast({
          title: '刷新失败',
          icon: 'none',
          duration: 1500
        });
      });
    }
    
    // 加载图书分类
    async function loadCategories() {
      try {

        await bookStore.fetchCategories();
        
        
        // 强制创建新的数组对象，确保Vue响应式更新
        const allCategories = [
          { id: 'all', name: '全部' }
        ];
        
        // 使用循环添加每一项，避免引用问题
        if (bookStore.categories && bookStore.categories.length > 0) {
          bookStore.categories.forEach(item => {
            allCategories.push({...item}); // 使用展开运算符创建新对象
          });
        }
        
        // 强制设置新的数组对象
        categories.value = allCategories;
        
        
      } catch (error) {
        console.error('加载分类失败:', error);
        // 设置默认分类，确保界面不会空白
        categories.value = [
          { id: 'all', name: '全部' },
          { id: '1', name: '文学', icon: 'icon-wenxue' },
          { id: '2', name: '科技', icon: 'icon-keji' }
        ];
      }
      
      // 尝试强制触发UI更新
      setTimeout(() => {
        // 这个微小的修改会让Vue检测到变化并重新渲染
        const temp = categories.value;
        categories.value = [];
        setTimeout(() => {
          categories.value = temp;
        }, 10);
      }, 100);
    }
    
    // 加载热门图书
    async function loadHotBooks() {
      try {
        await bookStore.fetchHotBooks({
          size: 6,
          page: 1
        });
      } catch (error) {
        console.error('加载热门图书失败:', error);
      }
    }
    
    // 加载新书
    async function loadNewBooks() {
      try {
        await bookStore.fetchNewBooks({
          size: 6,
          page: 1
        });
      } catch (error) {
        console.error('加载新书失败:', error);
      }
    }
    
    // 加载个性化推荐
    async function loadPersonalRecommendations() {
      try {
        // 获取用户信息
        const userInfo = uni.getStorageSync('userInfo');
        
        // 检查是否有登录用户
        if (userInfo && userInfo.id) {
          // 使用数字类型的用户ID
          const userId = parseInt(userInfo.id);
          
          // 只有当用户ID是有效数字时才请求个性化推荐
          if (!isNaN(userId) && userId > 0) {
            await bookStore.fetchPersonalRecommendations(userId, {
              size: 6,
              page: 1
            });
            return; // 成功获取后返回
          }
        }
        
        // 如果无法获取用户ID或ID无效，则仅加载热门图书

        bookStore.personalRecommendations = []; // 清空个性化推荐列表
      } catch (error) {
        console.error('加载个性化推荐失败:', error);
        // 个性化推荐失败不影响整体功能
        bookStore.personalRecommendations = [];
      }
    }
    
    // 切换分类
    function changeCategory(categoryId) {
      currentCategory.value = categoryId;
      // 根据分类刷新数据逻辑
    }
    
    // 点击轮播图处理
    function handleBannerClick(item) {
      switch (item.type) {
        case 'book':
          uni.navigateTo({
            url: `/pages/book-detail/book-detail?id=${item.targetId}`
          });
          break;
        case 'category':
          currentCategory.value = item.targetId;
          break;
        case 'promotion':
          uni.navigateTo({
            url: `/pages/promotion/promotion?id=${item.targetId}`
          });
          break;
        default:
          break;
      }
    }
    
    // 跳转到搜索页
    function goToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      });
    }
    
    // 跳转到图书详情页
    function goToBookDetail(bookId) {
      uni.navigateTo({
        url: `/pages/book-detail/book-detail?id=${bookId}`
      });
    }
    
    // 跳转到更多页面
    function goToMore(type) {
      let url = '';
      switch(type) {
        case 'hot':
          url = '/pages/book-list/book-list?type=hot';
          break;
        case 'new':
          url = '/pages/book-list/book-list?type=new';
          break;
        case 'recommendation':
          url = '/pages/book-list/book-list?type=recommendation';
          break;
        default:
          url = '/pages/book-list/book-list';
      }
      uni.navigateTo({ url });
    }
    
    // 加载更多图书
    function loadMore() {
      loadMoreStatus.value = 'loading';
      setTimeout(() => {
        loadMoreStatus.value = 'noMore';
      }, 1000);
    }
    
    // 图片错误处理函数
    function handleImageError() {
      // 图片错误处理逻辑
    }
    
    // 文本格式化函数
    function formatText(text, length = 30) {
      if (!text) return '';
      return text.length > length ? text.slice(0, length) + '...' : text;
    }
    
    
    // 确保在初始化时为bookStore创建空的个性化推荐数组
    if (!bookStore.personalRecommendations) {
      bookStore.personalRecommendations = [];
    }
    
    // 重命名切换分类函数，使其名称与return一致
    function handleCategoryChange(categoryId) {
      currentCategory.value = categoryId;
      // 根据分类刷新数据逻辑
    }
    
    // 注意:已经有了goToBookDetail函数声明，无需重复声明
    // 使用handleBookClick作为备用函数名，但不再创建新的goToBookDetail
    
    // 重命名加载更多函数，使其与返回值名称匹配
    const loadMoreBooks = loadMore;
    
    // 返回数据和方法
    return {
      bannerList,
      categories,
      currentCategory,
      handleCategoryChange, // 现在函数名匹配了
      bookStore: bookStore || useBookStore(), // 确保bookStore存在
      userStore, // 添加userStore供模板使用
      isLoading,
      loadMoreStatus,
      loadingText,
      onPullDownRefresh,
      loadMoreBooks, // 现在函数已经定义
      handleBannerClick,
      handleImageError,
      goToSearch,
      goToBookDetail, // 修改为模板中使用的名称
      checkLoginStatus, // 添加登录状态检查函数
      formatText
    };
  }
};
</script>

<style lang="scss">
.index-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  /* 搜索栏样式 */
  .search-container {
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    position: sticky;
    top: 0;
    z-index: 100;
    
    .search-box {
      height: 70rpx;
      background-color: #f2f2f2;
      border-radius: 35rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      
      .iconfont {
        font-size: 32rpx;
        color: #999999;
        margin-right: 10rpx;
      }
      
      .search-placeholder {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }
  
  /* 轮播图样式 */
  .banner-swiper {
    width: 100%;
    height: 300rpx;
    
    .banner-image {
      width: 100%;
      height: 100%;
    }
  }
  
  /* 分类导航样式 */
  .category-nav {
    background-color: #ffffff;
    padding: 20rpx 0;
    
    .category-scroll {
      white-space: nowrap;
      width: 100%;
      
      .category-item {
        display: inline-block;
        padding: 10rpx 30rpx;
        margin: 0 10rpx;
        font-size: 28rpx;
        color: #666666;
        position: relative;
        
        &.active {
          color: #0066ff;
          font-weight: 500;
          
          &:after {
            content: '';
            position: absolute;
            bottom: -4rpx;
            left: 30%;
            width: 40%;
            height: 4rpx;
            background-color: #0066ff;
            border-radius: 2rpx;
          }
        }
        
        &:first-child {
          margin-left: 20rpx;
        }
      }
    }
  }
  
  /* 加载状态样式 */
  .loading-container {
    padding: 40rpx 0;
  }
  
  /* 内容区域样式 */
  .content-container {
    padding: 20rpx 0;
    
    /* 区块通用样式 */
    .section-container {
      margin-bottom: 30rpx;
      background-color: #ffffff;
      padding: 20rpx;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      
      /* 区块标题样式 */
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        
        .section-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          position: relative;
          padding-left: 20rpx;
          
          &:before {
            content: '';
            position: absolute;
            left: 0;
            top: 25%;
            height: 50%;
            width: 8rpx;
            background-color: #0066ff;
            border-radius: 4rpx;
          }
        }
        
        .section-more {
          font-size: 24rpx;
          color: #999999;
          display: flex;
          align-items: center;
          
          .iconfont {
            font-size: 24rpx;
            margin-left: 4rpx;
          }
        }
      }
    }
    
    /* 横向滚动图书列表样式 */
    .book-scroll {
      white-space: nowrap;
      width: 100%;
      
      .book-card {
        display: inline-block;
        width: 200rpx;
        margin-right: 20rpx;
        vertical-align: top;
        
        .book-cover {
          width: 100%;
          height: 280rpx;
          border-radius: 8rpx;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        }
        
        .book-title {
          font-size: 26rpx;
          color: #333333;
          margin-top: 10rpx;
          white-space: normal;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          line-height: 1.4;
          height: 2.8em;
        }
        
        .book-rating {
          display: flex;
          align-items: center;
          margin-top: 6rpx;
          
          .rating-text {
            font-size: 22rpx;
            color: #ff9900;
            margin-left: 6rpx;
          }
        }
      }
    }
    
    /* 网格图书列表样式 */
    .book-grid {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      
      .book-item {
        width: 48%;
        margin-bottom: 20rpx;
        
        .book-cover {
          width: 100%;
          height: 240rpx;
          border-radius: 8rpx;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
        }
        
        .book-title {
          font-size: 26rpx;
          color: #333333;
          margin-top: 10rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .book-author {
          font-size: 22rpx;
          color: #666666;
          margin-top: 6rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .book-rating {
          display: flex;
          align-items: center;
          margin-top: 6rpx;
          
          .rating-text {
            font-size: 22rpx;
            color: #ff9900;
            margin-left: 6rpx;
          }
        }
      }
    }
    
    /* 列表图书样式 */
    .book-list {
      .book-list-item {
        display: flex;
        padding: 20rpx 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .book-cover {
          width: 160rpx;
          height: 220rpx;
          border-radius: 8rpx;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
          margin-right: 20rpx;
          flex-shrink: 0;
        }
        
        .book-info {
          flex: 1;
          overflow: hidden;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          
          .book-title {
            font-size: 30rpx;
            color: #333333;
            font-weight: 500;
            margin-bottom: 10rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .book-author {
            font-size: 26rpx;
            color: #666666;
            margin-bottom: 10rpx;
          }
          
          .book-desc {
            font-size: 24rpx;
            color: #999999;
            line-height: 1.5;
            margin-bottom: 10rpx;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .book-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .book-rating {
              display: flex;
              align-items: center;
              
              .rating-text {
                font-size: 22rpx;
                color: #ff9900;
                margin-left: 6rpx;
              }
            }
            
            .book-category {
              font-size: 22rpx;
              color: #0066ff;
              background-color: rgba(0, 102, 255, 0.1);
              padding: 4rpx 12rpx;
              border-radius: 20rpx;
            }
          }
        }
      }
    }
  }
  
  /* 底部加载区域样式 */
  .footer {
    padding: 30rpx 0;
    text-align: center;
  }
}
</style>
